import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_learn_vi/src/bean/bean_category.dart';
import 'package:flutter_learn_vi/src/bean/bean_day_stat.dart';
import 'package:flutter_learn_vi/src/bean/bean_rank.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/date_utils.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'mine_my_his_recoder_page.dart';
import 'mine_my_score_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/4.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
class MineMyScoreHisPage extends StatefulWidget {
  final MonthStatisticItemBean monthStatisticItemBean;
  final CategoryItemBean categoryItemBean;
  final String categoryOne;
  final StreamController<String> dateSelectStream;

  const MineMyScoreHisPage(
      {Key key,
      this.monthStatisticItemBean,
      this.categoryItemBean,
      this.categoryOne,
      this.dateSelectStream})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MineItem2State();
  }
}

class _MineItem2State extends State<MineMyScoreHisPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  StreamSubscription<String> _streamSubscription;

  //标签页面保活 或者称保持状态
  @override
  bool get wantKeepAlive => true;

  AnimationController _animationController;

  Animation<Offset> _animation;

  @override
  void initState() {
    super.initState();

    _animationController = new AnimationController(
        vsync: this, duration: Duration(milliseconds: 1200));

    _animation = new Tween(begin: Offset(0, -1), end: Offset(0, 0)).animate(
        CurvedAnimation(
            curve: Curves.fastOutSlowIn, parent: _animationController));
    getTopicHistoryist();
    if (widget.dateSelectStream != null) {
      _streamSubscription = widget.dateSelectStream.stream.listen((event) {
        ToastUtils.showToast("正在刷新数据");
        getTopicHistoryist();
      });
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    _streamSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (_list.length == 0) {
      return Container(
        child: NoDataWidget(
          text: "暂无数据",
        ),
      );
    }
    //一个列表 切记不要再使用 Scaffold
    //否则会拦截事件 失去滑动联动效果
    return Container(
      padding: EdgeInsets.only(top: 12),
      color: Colors.white,
      child: ListView.builder(
        //去除内边距
        padding: EdgeInsets.all(0),
        //列表子Item个数
        itemCount: _list.length,
        //每个子Item的布局构建
        itemBuilder: (BuildContext context, int index) {
          return buildBodyWidget(index);
        },
      ),
    );
  }

  //每个子Item的布局构建
  Widget buildBodyWidget(int index) {
    BeanDayStat beanDayStat = _list[index];

    //水波纹点击事件监听
    return InkWell(
      //手指点击抬起时的回调
      onTap: () {
        if (beanDayStat.extractingId == 0) {
          ToastUtils.showToast("暂不可查看详情");
          return;
        }
        NavigatorUtils.pushPage(
          context,
          MineMyScoreHisRecoderPage(
            extractingId: beanDayStat.extractingId,
          ),
        );
      },
      child: Container(
        padding: EdgeInsets.only(left: 10, right: 10),
        color: Colors.white,
        //线性布局左右排列
        child: Row(
          //主轴方向开始对齐 在这里是左对齐
          mainAxisAlignment: MainAxisAlignment.start,
          //交叉轴上开始对齐 在这里是顶部对齐
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //左侧的图片
            buildLeftImage(index, beanDayStat),
            //右侧的文本区域
            Expanded(child: buildRightTextArea(index, beanDayStat))
          ],
        ),
      ),
    );
  }

  ///左侧的图片区域
  Container buildLeftImage(int index, BeanDayStat beanDayStat) {
    int obtainScore = (beanDayStat.obtainScore / 10).toInt();
    Color color;
    IconData iconData;
    if (obtainScore > 90) {
      iconData = Icons.text_rotate_up_sharp;
      color = Colors.green;
    } else if (obtainScore <= 90 && obtainScore >= 60) {
      iconData = Icons.text_rotate_up_sharp;
      color = Colors.blue;
    } else {
      iconData = Icons.tag_faces_rounded;
      color = Colors.redAccent;
    }

    return Container(
      margin: EdgeInsets.only(right: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            width: 1,
            height: 6,
            color: index == 0 ? Colors.transparent : color,
          ),
          ClipOval(
            child: Container(
              width: 8,
              height: 8,
              color: color,
            ),
          ),
          Container(
            width: 1,
            height: 30,
            color: index == _list.length - 1 ? Colors.transparent : color,
          ),
        ],
      ),
    );
  }

  ///右侧的文本区域
  Expanded buildRightTextArea(int index, BeanDayStat beanDayStat) {
    double obtainScore = beanDayStat.obtainScore / 10;
    String timeStr = "${beanDayStat.answerTime}秒";
    if (beanDayStat.answerTime > 60) {
      timeStr =
          "${beanDayStat.answerTime ~/ 60}分${(beanDayStat.answerTime % 60).toInt()}秒";
    }
    String rightTips = "";
    Color rightTipsColor = Colors.black38;
    if (beanDayStat.extractingId > 0) {
      rightTips = "【点击查看详情】";
      rightTipsColor = Colors.blue;
    }
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            "${beanDayStat.createTime} 答题 $timeStr 获取 ${obtainScore.toStringAsFixed(0)}分 ",
            softWrap: true,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.right,
            style: TextStyle(fontSize: 14, color: rightTipsColor),
          ),
          SizedBox(
            height: 20,
          ),
        ],
      ),
    );
  }

  List<BeanDayStat> _list = [];

  ///查询我的答题记录
  Future<List<BeanDayStat>> getTopicHistoryist() async {
    String _currentSelectDate =
        ViDateUtils.formatDate(DateTime.now(), format: "yyyy-MM");
    Map<String, dynamic> monthMap = {
      "categoryOne": widget.categoryOne,
      "categoryTwo": widget.categoryItemBean.categoryCode,
      "sort": "TIMES",
      "date": "$myScoreCurrentSelectDate-01 00:00:00",
      "queryFlag": 2
    };

    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.myMyScoreQuestionRecoderUrl, queryParameters: monthMap);
    _list = [];
    if (statisRresponseInfo.success) {
      List list = statisRresponseInfo.data['list'];
      list.forEach((element) {
        _list.add(BeanDayStat.fromMap(element));
      });
      if (mounted) {
        setState(() {});
      }
      return _list;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return _list;
    }
  }
}
